import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, getOldToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    config.headers['Authorization'] = `Bearer ${getToken()}`
    // 如果是老伟班平台的接口 需要设置老token
    if (config.url.indexOf(process.env.VUE_APP_OLD_VEIBAN_BHOST) > -1) {
      if (getOldToken()) {
        config.headers['Authorization'] = getOldToken()
      }
    }
    // console.log('xxxx:', localStorage.getItem('companyInfo'))
    if (localStorage.getItem('companyInfo')) {
      config.headers['tenantId'] = (JSON.parse(localStorage.getItem('companyInfo')) || {}).tenantId
    }
    if (localStorage.getItem('userInfo')) {
      config.headers['deptId'] = (
        JSON.parse(localStorage.getItem('userInfo')) || {}
      ).deptId
    }

    // if (config.url.indexOf(process.env.VUE_APP_MINIO_ENDPOINT) > -1) {
    //   config.headers['Content-Type'] = `application/octet-stream`
    //   console.log('configconfig:', config, config.headers)
    // }
    // get时 url params endcode
    let url = config.url
    if (config.method === 'get' && config.params) {
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
    }
    config.url = url

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else if (res.code === 0 && response.config.url.indexOf(process.env.VUE_APP_OLD_VEIBAN_BHOST) >= 0) {
        // 老平台 的 错误代码  不提示message
        return res
      } else if (res.code === 180000) {
        // 老平台 的 错误代码  不提示message
        return Promise.reject(res.message)
      } else if (res.code === 401) {
        // 去登录
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      if (response.config.url.indexOf('api/session/user/login') > -1) {
        return {
          ...res.data,
          token: response.headers['nobug-sid'] || ''
        }
      }
      return res.data
    }
  },
  error => {
    console.log(error) // for debug
    let msg = error.message
    if (error.response.data && error.response.data.msg) {
      msg = error.response.data.msg
    }
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
